package com.game.serivce;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.Map.Entry;
import java.util.Random;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import net.SocketEnum;
import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.apache.mina.core.session.IoSession;

import com.component.code.CommonCode.PropIds;
import com.component.code.TishiManager;
import com.component.mode.Button;
import com.data.WDataConversion;
import com.data.third.DataService;
import com.dictionary.DictionaryTabel;
import com.game.android.AndroidService;
import com.game.model.ConfigDesk;
import com.game.model.ConfigRoomService;
import com.game.model.FactoryPai;
import com.game.model.Pai;
import com.game.rule.Rule;

/**
 * 房间桌子服务
 * @author wuxiaojian
 *
 */
public class RoomDeskService {
	private Logger logger = Logger.getLogger(RoomDeskService.class.getName());
	public ConfigDesk configDesk;
	public GameRoomService gameRoomeService;
	public DeskPlayerService[] deskPlayerServices;
	private ConfigRoomService configRoomService;
	public long chouShuiChi = 0l;// 抽水池
	public long normalFanFenChi = 0l;// 正常游戏返分池
	public long bossFen = 0l;
	
	
	public ConfigRoomService getConfigRoomService() {
		return configRoomService;
	}

	public void setConfigRoomService(ConfigRoomService configRoomService) {
		this.configRoomService = configRoomService;
	}
	/**当前游戏持续时长**/
	public float gameTime;
    /**当前状态剩余时间**/
	public float lastGameTime;
	
	public RoomDeskService(GameRoomService gameRoomeService,ConfigRoomService configRoomService, int deskNum){
		init(gameRoomeService,configRoomService,deskNum);
	}
	
	public void init(GameRoomService gameRoomeService,ConfigRoomService configRoomService,int deskNum) {
		this.configRoomService = configRoomService;
		this.gameRoomeService = gameRoomeService;
		configDesk = new ConfigDesk();
		configDesk.setRoomNum(gameRoomeService.configRoomService.isOpen);
		configDesk.setDeskNum(deskNum);
		//configDesk.setBossFen(0l);
		//configDesk.setNowRank(0);
		int seatCount = gameRoomeService.configRoomService.oneDeskhavePlayerCount;
		deskPlayerServices = new DeskPlayerService[seatCount];
		configDesk.setGameState(DictionaryTabel.Game_Sleep);
		//xipai();
		//setTimerTask();
	}
	
	public ConfigDesk getConfigDesk() {
		return configDesk;
	}

	public void setConfigDesk(ConfigDesk configDesk) {
		this.configDesk = configDesk;
	}

	/**
	 * 加入桌子
	 * @param basePlayer
	 * @return
	 */
	public synchronized boolean intoDesk(DeskPlayerService dps){
		try {
			//if (isCanJoinDesk()) {
				
				//获取座位号
				int seatNum = Rule.getNullSeat(deskPlayerServices);
				
				//该桌子已有人
				if (seatNum == -1)
					return false;
				
				//加入座位
				dps.playerService.deskPlayer.setSeatNum(seatNum);
				dps.playerService.deskPlayer.setDeskNum(configDesk.getDeskNum());
				//dps.playerService.deskPlayer.setRoomNum(configDesk.getRoomNum());
				dps.playerService.deskPlayer.setMoney(dps.playerService.deskPlayer.getBagInfo().getLong("2"));
				dps.playerService.deskPlayer.setChipShow(new int[gameRoomeService.configRoomService.chipType.length + 2]);
				//TODO 多余
				//dps.setPlayerService(dps.playerService);
				dps.roomDeskService = this;
				deskPlayerServices[seatNum] = dps;
				deskPlayerServices[seatNum].initDeskPlayerService(dps);
				//deskPlayerServices[seatNum] = new DeskPlayerService(dps);
				System.out.println("1111111->" + dps.hashCode());
				configDesk.setGameState(DictionaryTabel.Game_Wait);
				//初始化桌子信息
				initDesk(dps);
				
				return true;
			//}
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
		//加入失败
		return false;
	}
	
	/**重新加入桌子**/
	public void reIntoDesk(DeskPlayerService dps) {
		System.out.println(dps.playerService.deskPlayer.getPlayerId() + "：重连开始！！！");
		
		//初始化桌子信息
		initDesk(dps);
				
		System.out.println(dps.playerService.deskPlayer.getPlayerId() + "：重连结束！！！");
	}
	/**桌子初始化**/
	public void initDesk(DeskPlayerService dps) {
		
		
		JSONObject json = new JSONObject();
		json.put("playerId", dps.playerService.deskPlayer.getPlayerId());
		json.put("playerSex", dps.playerService.deskPlayer.getPlayerSex());
		json.put("nickName", dps.playerService.deskPlayer.getNickName());
		json.put("headUrl", dps.playerService.deskPlayer.getHeadUrl());
		json.put("vipLevel", dps.playerService.deskPlayer.getVipLevel());
		json.put("money", dps.playerService.deskPlayer.getMoney());
		dps.playerService.sendMessage(SocketEnum.playerI+ "@" + json.toString() + "@&");
		json.clear();
		//json.put("", value);
		//取得下注區域
		int betArea[] = gameRoomeService.configRoomService.chipType;
		for (int i = betArea.length - 1; i >= 0; i--) {
			if ((betArea[i] * 30) < dps.playerService.deskPlayer.getMoney()) {
				if (i == betArea.length - 1) {
					json.put("curBetIndex", i);
				} else {
					json.put("curBetIndex", i + 1);
				}
				break;
			}
		}
		json.put("bossFen", getConfigDesk().getBossFen());
		json.put("totalBossXue", getConfigDesk().getBossTotalXue());
		json.put("playerFen", dps.playerService.deskPlayer.getPlayerNowBossFen());
		json.put("nowRank", getConfigDesk().getNowRank());
		dps.playerService.sendMessage(SocketEnum.initDeskI+ "@" + json.toString() + "@&");
		json.clear();
		json.put("freeCount", 0);
		json.put("betIndex", 5);
		json.put("isFinish", 0);
		dps.playerService.sendMessage(SocketEnum.freeInfo+ "@" + json.toString() + "@&");
		json.clear();
		ArrayList<Pai> pai = FactoryPai.getInstance().paiList;
		json.put("0", pai.get(0));
		json.put("1", pai.get(1));
		json.put("2", pai.get(2));
		json.put("3", pai.get(3));
		json.put("4", pai.get(4));
		json.put("5", pai.get(5));
		json.put("6", pai.get(6));
		json.put("7", pai.get(7));
		json.put("8", pai.get(8));
		json.put("9", pai.get(9));
		json.put("10", pai.get(10));
		json.put("11", pai.get(11));
		//json.put("12", pai.get(12));
		dps.playerService.sendMessage(SocketEnum.paiList+ "@" + json.toString() + "@&");
		
	}
	/**离开桌子**/
	public void leaveDesk(DeskPlayerService dps) {
		if (dps.playerService.deskPlayer.getPlayerType() == DictionaryTabel.PlayerType_People) {
			if (configDesk.getGameState() > DictionaryTabel.Game_BeginJu && dps.playerService.deskPlayer.getBetInfo().size() > 0) {
				dps.playerService.deskPlayer.setState(DictionaryTabel.player_exit);
				return;
			}
		}
		deskPlayerServices[dps.playerService.deskPlayer.getSeatNum()] = null;
					
//		if (getPlayersCount() == 0) {
//			if (gameRoomeService.haveWaitPlayerDeskServices.contains(this)) {
//				gameRoomeService.haveWaitPlayerDeskServices.remove(this);
//			}
//		} else if (getPlayersCount() > 0 && getPlayersCount() < gameRoomeService.configRoom.oneDeskhavePlayerCount) {
//			if (!gameRoomeService.haveWaitPlayerDeskServices.contains(this)) {
//				gameRoomeService.haveWaitPlayerDeskServices.add(this);
//			}
//		}	
		
		if (dps.playerService.deskPlayer.getPlayerType() == DictionaryTabel.PlayerType_People) {	
			DataService.leaveDesk(dps.playerService.deskPlayer.getPlayerId(), dps.playerService.deskPlayer.getGameNum(), dps.playerService.deskPlayer.getRoomNum(), dps.playerService.deskPlayer.getDeskNum(), dps.playerService.deskPlayer.getSeatNum(), 0);	
			gameRoomeService.leaveRoom(dps);
		} else {
			//dps.sendMessage(SocketEnum.androidExitI, "");
		}
	}
	
//	/** 统一设置桌子上玩家的状态 **/
//	public void setPlayersStatus(int Nowstate,int nextState) {
//		try {
//			DeskPlayerService deskPlayerService;
//			for (int i = 0; i < deskPlayerServices.length; i++) {
//				deskPlayerService = deskPlayerServices[i];
//				if (deskPlayerService != null) {
//					if (deskPlayerService.deskPlayer.getState() == Nowstate)
//						deskPlayerService.deskPlayer.setState(nextState);
//				}
//			}
//		} catch (Exception e) {
//			e.printStackTrace();
//			logger.error(e.getMessage(), e);
//		}
//	}
//	/** 发送消息给该桌子全部玩家 **/
//	public void sendMessageToAll(int messageHead, String messageContent) {
//		try {
//			DeskPlayerService deskPlayerService;
//			for (int i = 0; i < deskPlayerServices.length; i++) {
//				deskPlayerService = deskPlayerServices[i];
//				if (deskPlayerService != null) {
//					deskPlayerService.sendMessage(messageHead, messageContent);
//				}
//			}
//		} catch (Exception e) {
//			logger.error(e.getMessage(), e);
//		}
//	}
	
//	/** 发送消息给该桌子其余玩家 **/
//	public void sendMessageToAllButMe(int messageHead, String messageContent, long playerId) {
//		try {
//			DeskPlayerService deskPlayerService;
//			for (int i = 0; i < deskPlayerServices.length; i++) {
//				deskPlayerService = deskPlayerServices[i];
//				if (deskPlayerService != null && deskPlayerService.deskPlayer.getPlayerId() != playerId) {
//					deskPlayerService.sendMessage(messageHead, messageContent);
//				}
//			}
//		} catch (Exception e) {
//			logger.error(e.getMessage(), e);
//		}
//	}
	
//	protected ScheduledExecutorService scheduExec = Executors.newSingleThreadScheduledExecutor();
//	private void setTimerTask() {
//		Runnable task = new Runnable() {
//			public void run() {
//				try {
//					if (configDesk.getGameState() > DictionaryTabel.Game_Close) {
//						deal();
//					}
//				} catch (Exception e) {
//					logger.error(e.getMessage(), e);
//				}
//			}
//		};
//		scheduExec.scheduleWithFixedDelay(task, 0, 500, TimeUnit.MILLISECONDS);
//
//	}
//	
//	private void deal() {
//		try {
//			switch (configDesk.getGameState()) {
//			case DictionaryTabel.Game_Sleep:
//				clean_andorid();
//				break;
//			case DictionaryTabel.Game_BeginJu:
//				game_BeginJu();
//				break;
//			case DictionaryTabel.Game_Fapai:
//				game_Fapai();
//				break;
//			case DictionaryTabel.Game_WaitOpen:
//				Game_WaitOpen();
//				break;
//			case DictionaryTabel.Game_Open:
//				Game_Open();
//				break;
//			case DictionaryTabel.Game_WaitJieSuan:
//				Game_WaitJieSuan();
//				break;	
//			case DictionaryTabel.Game_JieSuan:
//				Game_JieSuan();
//				break;
//			default:
//				break;
//			}
//			gameTime = gameTime + 0.5f;
//		} catch (Exception e) {
//			logger.error(e.getMessage(), e);
//		}
//	}
//	/**
//	 * 游戏状态-等待玩家加入
//	 */
//	private void game_WaitPlayer() {
//		gameTimeChange();
//		if (lastGameTime <= 0) {
//			try {
//				configDesk.setGameState(DictionaryTabel.Game_BeginJu);
//				setPlayersStatus(DictionaryTabel.player_waitNextJu, DictionaryTabel.player_waitXiaZhu);
//			} catch (Exception e) {
//				logger.error(e.getMessage(), e);
//			}
//		}
//	}
//	/**
//	 * 游戏状态-开始游戏
//	 */
//	private void game_BeginJu() {
//		configDesk.getTotalBetInfo().clear();
//		configDesk.getSpList().clear();
//		configDesk.getOpenSub().clear();
//		configDesk.setGameState(DictionaryTabel.Game_Xiazhu);
//		lastGameTime = gameRoomeService.configRoom.gameTimeXiaZhuTime;
//		for (int i = 0; i < deskPlayerServices.length; i ++) {
//			if (deskPlayerServices[i] != null) {
//				Rule.changeChipShow(deskPlayerServices[i].deskPlayer, gameRoomeService.configRoom, 0);
//				deskPlayerServices[i].sendMessage(SocketEnum.buttonShowI,  WDataConversion.intArrToString(deskPlayerServices[i].deskPlayer.getChipShow(), ","));
//				deskPlayerServices[i].sendMessage(SocketEnum.beginI, "");
//				deskPlayerServices[i].sendMessage(SocketEnum.daojishiI, ((int) lastGameTime) + "");
//				deskPlayerServices[i].deskPlayer.setState(DictionaryTabel.player_xiazhu);
//			}
//		}
//	}
//	/**
//	 * 游戏状态-正在下注
//	 */
//	private void game_Xiazhu() {
//		gameTimeChange();
//		//下注结束
//		if (lastGameTime <= 0) {
//			configDesk.setGameState(DictionaryTabel.Game_WaitFapai);
//			lastGameTime = gameRoomeService.configRoom.gameTimeWaitFaPaiTime;
//			for (int i = 0; i < deskPlayerServices.length; i ++) {
//				if (deskPlayerServices[i] != null && deskPlayerServices[i].deskPlayer.getState() == DictionaryTabel.player_xiazhu) {
//					deskPlayerServices[i].sendMessage(SocketEnum.endBetI, "");
//					if (deskPlayerServices[i].deskPlayer.getBetInfo().size() > 0) {
//						deskPlayerServices[i].deskPlayer.setNoOperateCount(0);
//						deskPlayerServices[i].deskPlayer.setState(DictionaryTabel.player_waitOpen);
//						if (deskPlayerServices[i].jieSuan(PropIds.GOLD.getValue(), -1 * deskPlayerServices[i].deskPlayer.getTotalMoney()) == -1) {
//							deskPlayerServices[i].sendMessage(SocketEnum.infoI, TishiManager.Tishi_T_MoneyException);
//							deskPlayerServices[i].getSession().close(false);
//						}
//					} else {
//						deskPlayerServices[i].deskPlayer.setNoOperateCount(deskPlayerServices[i].deskPlayer.getNoOperateCount() + 1);
//						if (deskPlayerServices[i].deskPlayer.getNoOperateCount() >= gameRoomeService.configRoom.outRoomCount) {
//							deskPlayerServices[i].sendMessage(SocketEnum.infoI, TishiManager.getTishiT("由于您连续"+gameRoomeService.configRoom.outRoomCount 
//									+ "局未下注,已经被请出房间!", TishiManager.WINDOW_T, new ArrayList<Button>() {
//										{
//											add(new Button(TishiManager.tishiButton_returnHall, null));
//										}
//									}));
//							deskPlayerServices[i].getSession().close(false);
//							continue;
//						}
//						deskPlayerServices[i].deskPlayer.setState(DictionaryTabel.player_waitNextJu);
//						deskPlayerServices[i].deskPlayer.getPreBetInfo().clear();
//						deskPlayerServices[i].deskPlayer.setPreTotalMoney(0);
//					}
//				}
//			}
//		}
//	}
//	/**
//	 * 游戏状态-等待发牌
//	 */
//	 private void game_waitFapai() {
//		 gameTimeChange();
//		 if (lastGameTime <= 0) {
//			 configDesk.setGameState(DictionaryTabel.Game_Fapai);
//			 lastGameTime = gameRoomeService.configRoom.gameTimeFaPaiTime;
//		 }
//	 }
//	/**
//	 * 游戏状态-正在发牌
//	 */
//	private void game_Fapai() {
//		gameTimeChange();
//		if (lastGameTime <= 0) {
//			int card = configDesk.getCards().remove(0);
//			configDesk.getSpList().add(card);
//			
//			if (configDesk.getSpList().size() == 1 || configDesk.getSpList().size() == 3) {
//				for (int i = 0; i < deskPlayerServices.length; i ++) {
//					if (deskPlayerServices[i] != null && deskPlayerServices[i].deskPlayer.getPlayerType() == DictionaryTabel.PlayerType_People) {
//						deskPlayerServices[i].sendMessage(SocketEnum.fapaiI, "0," + card + "," + Rule.getDianShu(configDesk.getSpList(), 0) + "," + configDesk.getCards().size());
//					}
//				}
//			} else if (configDesk.getSpList().size() == 2) {
//				for (int i = 0; i < deskPlayerServices.length; i ++) {
//					if (deskPlayerServices[i] != null && deskPlayerServices[i].deskPlayer.getPlayerType() == DictionaryTabel.PlayerType_People) {
//						deskPlayerServices[i].sendMessage(SocketEnum.fapaiI, "1," + card + "," + Rule.getDianShu(configDesk.getSpList(), 1) + "," + configDesk.getCards().size());
//					}
//				}
//			} else if (configDesk.getSpList().size() == 4) {
//				for (int i = 0; i < deskPlayerServices.length; i ++) {
//					if (deskPlayerServices[i] != null && deskPlayerServices[i].deskPlayer.getPlayerType() == DictionaryTabel.PlayerType_People) {
//						deskPlayerServices[i].sendMessage(SocketEnum.fapaiI, "1," + card + "," + Rule.getDianShu(configDesk.getSpList(), 1) + "," + configDesk.getCards().size());
//					}
//				}
//				//判断是否增牌
//				int addType = Rule.getAddType(configDesk.getSpList());
//				if (addType == 0) {
//					configDesk.getSpList().add(0);
//					configDesk.getSpList().add(0);
//					configDesk.setGameState(DictionaryTabel.Game_WaitOpen);
//					lastGameTime = gameRoomeService.configRoom.gameTimeWaitFaPaiTime;
//					setPlayersStatus(DictionaryTabel.player_waitOpen, DictionaryTabel.player_open);
//					return;
//				} else if (addType == 2) {
//					configDesk.getSpList().add(0);
//				}
//			} else if (configDesk.getSpList().size() == 5) {
//				for (int i = 0; i < deskPlayerServices.length; i ++) {
//					if (deskPlayerServices[i] != null && deskPlayerServices[i].deskPlayer.getPlayerType() == DictionaryTabel.PlayerType_People) {
//						deskPlayerServices[i].sendMessage(SocketEnum.fapaiI, "0," + card + "," + Rule.getDianShu(configDesk.getSpList(), 0) + "," + configDesk.getCards().size());
//					}
//				}
//				//判断是否增牌
//				int addType = Rule.getAddType(configDesk.getSpList());
//				if (addType == 0) {
//					configDesk.getSpList().add(0);
//					configDesk.setGameState(DictionaryTabel.Game_WaitOpen);
//					lastGameTime = gameRoomeService.configRoom.gameTimeWaitFaPaiTime;
//					setPlayersStatus(DictionaryTabel.player_waitOpen, DictionaryTabel.player_open);
//					return;
//				}
//			} else if (configDesk.getSpList().size() == 6) {
//				for (int i = 0; i < deskPlayerServices.length; i ++) {
//					if (deskPlayerServices[i] != null && deskPlayerServices[i].deskPlayer.getPlayerType() == DictionaryTabel.PlayerType_People) {
//						deskPlayerServices[i].sendMessage(SocketEnum.fapaiI, "1," + card + "," + Rule.getDianShu(configDesk.getSpList(), 1) + "," + configDesk.getCards().size());
//					}
//				}
//				configDesk.setGameState(DictionaryTabel.Game_WaitOpen);
//				lastGameTime = gameRoomeService.configRoom.gameTimeWaitFaPaiTime;
//				setPlayersStatus(DictionaryTabel.player_waitOpen, DictionaryTabel.player_open);
//				return;
//			}
//			lastGameTime = gameRoomeService.configRoom.gameTimeFaPaiTime;
//		}
//	}
//	
//	/**
//	 * 游戏状态-等待开奖
//	 */
//	private void Game_WaitOpen() {
//		gameTimeChange();
//		if (lastGameTime <= 0) {
//			configDesk.setGameState(DictionaryTabel.Game_Open);
//			setPlayersStatus(DictionaryTabel.player_open, DictionaryTabel.player_waitJiesuan);
//		}
//	}
//	/**
//	 * 游戏状态-系统开奖
//	 */
//	private void Game_Open() {
//		//0闲对1闲天王2闲3和4庄天王5庄6庄对
//		ArrayList<Integer> openSub = Rule.openSub(configDesk.getSpList());
//		int openType = 0;
//		if (!openSub.contains(3)) {
//			if (openSub.contains(0) || openSub.contains(1) || openSub.contains(2))
//				openType = -1;
//			else if (openSub.contains(4) || openSub.contains(5) || openSub.contains(6))
//				openType = 1;
//		}
//		
//		configDesk.getHistory().add(openType);
//		configDesk.getOpenSub().addAll(openSub);
//		
//		for (int i = 0; i < deskPlayerServices.length; i ++) {
//			if (deskPlayerServices[i] != null ) {
//				deskPlayerServices[i].sendMessage(SocketEnum.openI, WDataConversion.IntegerListToString(openSub, ","));
//			}
//		}
//		
//		configDesk.setGameState(DictionaryTabel.Game_WaitJieSuan);
//		lastGameTime = gameRoomeService.configRoom.gameTimeWaitJieSuanTime;
//	}
//	/**
//	 * 游戏状态-等待结算
//	 */
//	private void Game_WaitJieSuan() {
//		gameTimeChange();
//		if (lastGameTime <= 0) {
//			configDesk.setGameState(DictionaryTabel.Game_JieSuan);
//			setPlayersStatus(DictionaryTabel.player_waitJiesuan, DictionaryTabel.player_jieSuan);
//		}
//	}
//	/**
//	 * 游戏状态-正在结算
//	 */
//	private void Game_JieSuan() {
//		ArrayList<Integer> openSub = configDesk.getOpenSub();
//		for (int i = 0; i < deskPlayerServices.length; i ++) {
//			if (deskPlayerServices[i] != null ) {
//				if (deskPlayerServices[i].deskPlayer.getBetInfo().size() > 0) {
//					long tBetMoney = deskPlayerServices[i].deskPlayer.getTotalMoney();
//					long winMoney = 0l;
//					//Iterator<Entry<Integer, HashMap<Integer, Integer>>> ite = deskPlayerServices[i].deskPlayer.getBetInfo().entrySet().iterator();
//					Iterator<Entry<Integer, Long>> ite = deskPlayerServices[i].deskPlayer.getBetInfo().entrySet().iterator();
//					while (ite.hasNext()) {
//						Entry<Integer, Long> entry = ite.next();
//						//tBetMoney += entry.getValue();
//						
//						if (openSub.contains(3)) {
//							if (entry.getKey() == 2 || entry.getKey() == 5)
//								winMoney += entry.getValue();
//						}
//						
//						if (openSub.contains(entry.getKey())) {
//							winMoney += entry.getValue() * gameRoomeService.configRoom.subChip[entry.getKey()];
//						}
//						
//						/*Entry<Integer, HashMap<Integer, Integer>> entry = ite.next();
//						Iterator<Entry<Integer, Integer>>  _ite = entry.getValue().entrySet().iterator();
//						
//						long betMoney = 0l;
//						while (_ite.hasNext()) {
//							Entry<Integer, Integer> _entry = _ite.next();
//							betMoney += _entry.getKey() * _entry.getValue(); 
//						}
//						
//						tBetMoney += betMoney;
//						if (openSub.contains(entry.getKey())) {
//							winMoney += betMoney * gameRoomeService.configRoom.subChip[entry.getKey()];
//						}*/
//					}					
//					winMoney = deskPlayerServices[i].jieSuan(PropIds.GOLD.getValue(), winMoney);
//					//deskPlayerServices[i].sendMessage(SocketEnum.jiesuanI, winMoney + "");
//					//winMoney = PlayerDBService.getInstance().updatePropInfo(deskPlayerServices[i], PropIds.GOLD.getValue(), winMoney - totalMoney, 1);
//					if (winMoney == -1) {
//						//结算失败
//						deskPlayerServices[i].changePropNum(2, tBetMoney);
//						deskPlayerServices[i].sendMessage(SocketEnum.jiesuanI, tBetMoney + "");
//						deskPlayerServices[i].sendMessage(SocketEnum.infoI, TishiManager.Tishi_T_MoneyException);
//						leaveDesk(deskPlayerServices[i]);
//					} else {
//						deskPlayerServices[i].changePropNum(2, tBetMoney + winMoney);
//						deskPlayerServices[i].sendMessage(SocketEnum.jiesuanI, tBetMoney + winMoney + "");
//					}
//					
//					deskPlayerServices[i].sendMessage(SocketEnum.bagI, deskPlayerServices[i].getPropNum(1) + "," + deskPlayerServices[i].getPropNum(2));
//					deskPlayerServices[i].deskPlayer.getPreBetInfo().clear();
//					deskPlayerServices[i].deskPlayer.getPreBetInfo().putAll(deskPlayerServices[i].deskPlayer.getBetInfo());
//					deskPlayerServices[i].deskPlayer.setPreTotalMoney(deskPlayerServices[i].deskPlayer.getTotalMoney());
//				}
//				
//				deskPlayerServices[i].sendMessage(SocketEnum.flyChipI, "");
//				
//				deskPlayerServices[i].deskPlayer.getBetInfo().clear();
//				deskPlayerServices[i].deskPlayer.setTotalMoney(0);
//				
//				if (deskPlayerServices[i].deskPlayer.getState() != DictionaryTabel.player_exit)
//					deskPlayerServices[i].deskPlayer.setState(DictionaryTabel.player_waitNextJu);
//			}
//			
//		}	
//		
//		configDesk.setGameState(DictionaryTabel.Game_EndJu);
//		lastGameTime = gameRoomeService.configRoom.gameTimeJieSuanTime;
//	}
//	/**游戏状态-结算结束**/
//	private void Game_EndJu() {
//		gameTimeChange();
//		if (lastGameTime == 1.0f) {
//			if (configDesk.getCards().size() <= 52) {
//				xipai();
//			}
//			for (int i = 0; i < deskPlayerServices.length; i ++) {
//				if (deskPlayerServices[i] != null) {
//					deskPlayerServices[i].sendMessage(SocketEnum.endI, "");
//					deskPlayerServices[i].sendMessage(SocketEnum.historyI, WDataConversion.IntegerListToString(configDesk.getHistory(), ","));
//					
//					if (deskPlayerServices[i].deskPlayer.getState() == DictionaryTabel.player_exit) {
//						leaveDesk(deskPlayerServices[i]);
//						continue;
//					}
//						
//					if (deskPlayerServices[i].getPropNum(2) < gameRoomeService.configRoom.roomLimitMoneyMin) {
//						if (deskPlayerServices[i].deskPlayer.getPlayerType() == DictionaryTabel.PlayerType_Android) {
//							if (Math.random() < gameRoomeService.configRoom.androidExitRate) {
//								AndroidService androidService = (AndroidService) deskPlayerServices[i];
//								androidService.changeAndroidInfo();
//							}
//						} else {
//							deskPlayerServices[i].sendMessage(SocketEnum.infoI, TishiManager.Tishi_T_MoneyTooLow);
//							deskPlayerServices[i].getSession().close(false);
//						}
//					} else if (deskPlayerServices[i].getPropNum(2) > gameRoomeService.configRoom.roomLimitMoneyMax) {
//						if (deskPlayerServices[i].deskPlayer.getPlayerType() == DictionaryTabel.PlayerType_Android) {
//							if (Math.random() < gameRoomeService.configRoom.androidExitRate) {
//								AndroidService androidService = (AndroidService) deskPlayerServices[i];
//								androidService.changeAndroidInfo();
//							}
//						} else {
//							deskPlayerServices[i].sendMessage(SocketEnum.infoI, TishiManager.Tishi_T_MoneyTooHigh);
//							deskPlayerServices[i].getSession().close(false);
//						}
//					}
//				}
//			}
//		} else if (lastGameTime <= 0) {
//			if (configDesk.isDelayClose()) {
//				closeDesk(configDesk.getCloseDeskMessage(), true);
//				return;
//			}
//			
//			if (configDesk.isDelayReStrat()) {
//				startDesk(configDesk.getCloseDeskMessage(), true);
//				return;
//			}
//			
//			configDesk.setGameState(DictionaryTabel.Game_BeginJu);
//		}
//	}
//	
//
//	/** 洗牌 **/
//	private void xipai() {
//		try {
//			String ss = "";
//			configDesk.getCards().clear();
//			for(int k = 0 ; k < gameRoomeService.configRoom.cardNum; k++){
//				for (int i = 0; i < 4; i++) {
//					for (int j = 1; j <= 10; j++) {
//						configDesk.getCards().add((i + 1) * 100 + j);
//						ss = ss + ", " + ((i + 1) * 100 + j);
//					}
//
//					for (int j = 2; j < 5; j++) {
//						configDesk.getCards().add((i + 1) * 100 + j * 10);
//						ss = ss + ", " + ((i + 1) * 100 + j);
//					}
//				}
////				configDesk.getCards().add(1);
//			}
//			Collections.shuffle(configDesk.getCards(), new Random());// 洗牌
//			configDesk.getHistory().clear();
//		} catch (Exception e) {
//			logger.error(e.getMessage(), e);
//		}
//	}
//	
//	private void gameTimeChange() {
//		lastGameTime = lastGameTime - 0.5f;
//	}
//	
//	/** 统一设置桌子上玩家的状态 **/
//	private boolean isCanJoinDesk(){
//		if (configDesk.isDelayClose())
//			return false;
//		return true;
//	}
//	
	/** 得到桌子上玩家的数量（不包括电脑） **/
	public int getRealPlayersCount() {
		int c = 0;
		try {
			for (int i = 0; i < deskPlayerServices.length; i++) {
				if (deskPlayerServices[i] != null && deskPlayerServices[i].playerService.deskPlayer.getPlayerType() == DictionaryTabel.PlayerType_People) {
					c++;
				}
			}
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
		return c;
	}
	
//	/** 桌子开始 **/
//	public void begin(IoSession session,String content) {
//		try {
//			int seatNum = Integer.valueOf(session.getAttribute("seatNum") + "");
//			deskPlayerServices[seatNum].begin(content);
//		} catch (Exception e) {
//			// TODO: handle exception
//			throw e;
//		}
//	}
	
	/** 得到桌子上玩家的数量（包括电脑） **/
	public int getPlayersCount() {
		int c = 0;
		try {
			for (int i = 0; i < deskPlayerServices.length; i++) {
				if (deskPlayerServices[i] != null) {
					c++;
				}
			}
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
		return c;
	}
	
//	public void closeDesk(String closeMessage, boolean closeNow){
//		configDesk.setCloseDeskMessage(closeMessage);
//		if (!closeNow)
//			configDesk.setDelayClose(true);
//		else
//		{
//			String message = TishiManager.getTishiT(closeMessage, TishiManager.WINDOW_T, new ArrayList<Button>(){
//				{
//					add(new Button(TishiManager.tishiButton_returnHall, null));
//				}
//			});
//			for(int i = 0; i < deskPlayerServices.length; i ++){
//				if (deskPlayerServices[i] != null){
//					deskPlayerServices[i].sendMessage(SocketEnum.infoI, message);
//					leaveDesk(deskPlayerServices[i]);
//				}
//			}
//			
//			configDesk.setGameState(DictionaryTabel.Game_Close);
//			lastGameTime = 0;
//			gameTime = 0;
//			configDesk.setDelayClose(false);
//		}
//	}
	
//	public void startDesk(String closeMessage, boolean startNow){
//		configDesk.setCloseDeskMessage(closeMessage);
//		if (!startNow)
//			configDesk.setDelayReStrat(true);
//		else
//		{
//			String message = TishiManager.getTishiT(closeMessage, TishiManager.WINDOW_T, new ArrayList<Button>(){
//				{
//					add(new Button(TishiManager.tishiButton_ok, null));
//				}
//			});
//			
//			for(int i = 0; i < deskPlayerServices.length; i ++){
//				if (deskPlayerServices[i] != null){
//					deskPlayerServices[i].sendMessage(SocketEnum.infoI, message);
//					leaveDesk(deskPlayerServices[i]);
//				}
//			}
//			
//			configDesk.setGameState(DictionaryTabel.Game_Sleep);
//			lastGameTime = 0;
//			gameTime = 0;
//			configDesk.setDelayReStrat(false);
//		}
//	}
	
	private void clean_andorid() {
		for(int i = 0; i < deskPlayerServices.length; i ++){
			if (deskPlayerServices[i] != null){
				leaveDesk(deskPlayerServices[i]);
			}
		}
	}
	public synchronized void addChouShuiChi(float changeNum) {
		chouShuiChi += Math.round(changeNum);
	}

	public synchronized void addNormalFanFenChi(float changeNum) {
		normalFanFenChi += Math.round(changeNum);
	}
	public synchronized void autoReSetShuZhi(long myTotalBet, boolean isInFreeOpenAward) {
		if (!isInFreeOpenAward) {
			addNormalFanFenChi(getConfigRoomService().normalFanFenRate * myTotalBet);
			addChouShuiChi(getConfigRoomService().chouShuiChiRate * myTotalBet);
		}

		// System.out.println("************************");
		// System.out.println("开始自动调整抽水比例");
		// System.out.println("正常返分抽水比例:" + normalFanFenRate);
		// System.out.println("抽水池抽水比例:" +
		// getConfigRoomService().chouShuiChiRate);
		// System.out.println("************************");

	}

	public synchronized void addNowRankBossXue(long bossXue) {
		addBossXue(getConfigRoomService().addBossXue * bossXue);
		
	}
	private void addBossXue(float f) {
		bossFen += Math.round(f);
		configDesk.setBossFen(bossFen);
		if (configDesk.getNowRank() == DictionaryTabel.zhongcao) {
			if (configDesk.getBossFen() >= DictionaryTabel.zhongcaoX) {
				
				configDesk.setGameState(DictionaryTabel.Game_nextRank);
				configDesk.setNowRank(DictionaryTabel.liandan);
				configDesk.setBossTotalXue(DictionaryTabel.liandanX);
				
			}
		}
		if (configDesk.getNowRank() == DictionaryTabel.liandan) {
			if (configDesk.getBossFen() >= DictionaryTabel.liandanX) {
				configDesk.setGameState(DictionaryTabel.Game_nextRank);
				configDesk.setNowRank(DictionaryTabel.jiuzhixianzhi);
				configDesk.setBossTotalXue(DictionaryTabel.jiuzhixianzhiX);
			}
		}
		if (configDesk.getNowRank() == DictionaryTabel.jiuzhixianzhi) {
			if (configDesk.getBossFen() >= DictionaryTabel.jiuzhixianzhiX) {
				configDesk.setGameState(DictionaryTabel.Game_nextRank);
			}
		}
	}
}
